<?php
namespace App\Api\Helpers;
use \App\Api\ErrCode;

trait ApiResponse{

    protected $responseSuccessCode = ErrCode::OK;

    protected $responseFieldMsg = 'msg';

    protected $responseFieldData = 'data';

    protected $responseFieldCode = 'code';

    protected $responseFieldTrace = 'trace';

    protected $responseFieldMeta = 'meta';

    /**
     *
     * @param string $message
     * @param mixed $data
     * @param mixed $trace
     * @param mixed $meta
     * @return array
     */
    protected function getResponseSuccess($data = null, string $message = 'ok', $trace = null, $meta = null)
    {
        return $this->getResponseBase($this->responseSuccessCode, $message, $data, $trace, $meta);
    }

    /**
     *
     * @param int $code
     * @param string $message
     * @param mixed $data
     * @param mixed $trace
     * @param mixed $meta
     * @return array
     */
    protected function getResponseFail(int $code, string $message = 'fail', $data = null, $trace = null, $meta = null)
    {
        return $this->getResponseBase($code, $message, $data, $trace, $meta);
    }

    /**
     *
     * @param int $code
     * @param string $message
     * @param mixed $data
     * @param mixed $trace
     * @param mixed $meta
     * @return array
     */
    protected function getResponseBase(int $code, string $message, $data, $trace = null, $meta = null)
    {
        $isDebug = (bool) env('APP_DEBUG');
        $return[$this->responseFieldMsg] = $message;
        $return[$this->responseFieldData] = $data;
        $return[$this->responseFieldCode] = $code;
        if ($isDebug) {
            $return[$this->responseFieldTrace] = $trace;
            $return[$this->responseFieldMeta] = $meta;
            $return['sql'] = \App\Debugs::$sqls;
            $return['debug'] = \App\Debugs::$debugs;
        }
        return $return;
    }
}